package cn.sytton.taffe.framework.xss;

import cn.hutool.core.util.StrUtil;
import org.springframework.http.server.PathContainer;
import org.springframework.web.util.pattern.PathPatternParser;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class XssFilter implements Filter {

    private List<String> excludes = new ArrayList<>();

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        if(handleExcludeURL(req)){
            filterChain.doFilter(request, response);
            return;
        }

        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        filterChain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request) {
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes) {
            if (new PathPatternParser().parse(pattern).matches(PathContainer.parsePath(url))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig){
        String excludesParams = filterConfig.getInitParameter("excludes");
        if (StrUtil.isNotEmpty(excludesParams)) {
            excludes =  Arrays.asList(excludesParams.split(","));
        }
    }

    @Override
    public void destroy() {}

}
